/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.produk;

import com.x3.purchasing.account.Account;
import com.x3.purchasing.account.AccountDAO;
import com.x3.purchasing.account.AccountDAOImpl;
import com.x3.purchasing.common.ClassApplicationModule;
import com.x3.purchasing.kategori.Kategori;
import com.x3.purchasing.kategori.KategoriDAO;
import com.x3.purchasing.kategori.KategoriDAOImpl;
import com.x3.purchasing.vendor.Vendor;
import com.x3.purchasing.vendor.VendorDAO;
import com.x3.purchasing.vendor.VendorDAOImpl;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.image.AImage;
import org.zkoss.image.Image;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Detail;
import org.zkoss.zul.Div;
import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Vbox;

/**
 *
 * @author kris
 */
public class ProdukWnd extends ClassApplicationModule {

    private Textbox txtKode;
    private Textbox txtNama;
    private Textbox txtKeterangan;
    private Textbox txtKeteranganLengkap;
    private Doublebox txtHarga;
    private Combobox cmbKategori;
    private Fileupload fileUpload;
    private Label lblUploadStatus;
    private Listbox listboxData;
    private AccountDAO accountDAO;
    private VendorDAO vendorDAO;
    private KategoriDAO kategoriDAO;
    private ProdukDAO produkDAO;
    private Produk produkEdit;
    private Media media;
    private Account account;
    private Grid grid;
    private Rows rows;
    private Session session;
    private DecimalFormat df = new DecimalFormat("#0,000.00");

    public void onCreate() throws InterruptedException, Exception {
        accountDAO = new AccountDAOImpl();
        vendorDAO = new VendorDAOImpl();
        kategoriDAO = new KategoriDAOImpl();
        produkDAO = new ProdukDAOImpl();
        txtKode = (Textbox) this.getFellow("txtKode");
        txtNama = (Textbox) this.getFellow("txtNama");
        txtKeterangan = (Textbox) this.getFellow("txtKeterangan");
        txtKeteranganLengkap = (Textbox) this.getFellow("txtKeteranganLengkap");
        cmbKategori = (Combobox) this.getFellow("cmbKategori");
        fileUpload = (Fileupload) this.getFellow("fileUpload");
        lblUploadStatus = (Label) this.getFellow("lblUploadStatus");
        listboxData = (Listbox) this.getFellow("listboxData");
        txtHarga = (Doublebox) this.getFellow("txtHarga");
        grid = (Grid) this.getFellow("grid");
        rows = new Rows();
        session = Sessions.getCurrent();
        account = (Account) session.getAttribute("ACC_LOGIN");
        this.loadDataKategori();
        this.loadDataProduk();
    }

    public void loadDataProduk() throws Exception {
        try {
            Vendor vendor = vendorDAO.getByAccount(account.getId());
            try {
                if (grid.getRows() != null) {
                    grid.getRows().getChildren().clear();
                }
                List<Produk> datas = produkDAO.gets(vendor.getId());
                for (final Produk produk : datas) {
                    Row row = new Row();
                    Detail detail = new Detail();
                    detail.setOpen(false);
                    Hbox hbox = new Hbox();
                    //Cek gambar
                    if (produk.getFileGambar() != null) {
                        if (produk.getFileGambar().available() > 0) {
                            Image image = new AImage("image", produk.getFileGambar());
                            org.zkoss.zul.Image img = new org.zkoss.zul.Image();
                            img.setContent(image);
                            img.setHeight("120px");
                            img.setWidth("150px");
                            hbox.appendChild(img);
                        }
                    } else {
                        Label lblError = new Label("Gambar tidak tersedia");
                        lblError.setStyle("color:red;");
                        hbox.appendChild(lblError);
                    }

                    Vbox vbox = new Vbox();
                    vbox.appendChild(new Label("Kode : " + produk.getKode()));
                    vbox.appendChild(new Label("Keterangan : " + produk.getKeterangan()));
                    vbox.appendChild(new Label("Keterangan Lengkap: " + produk.getKeteranganLengkap()));
                    hbox.appendChild(vbox);
                    detail.appendChild(hbox);

                    row.appendChild(new Label(produk.getNama()));
                    row.appendChild(new Label(df.format(produk.getHargaSatuan())));

                    Toolbarbutton btnEdit = new Toolbarbutton();
                    btnEdit.setId("btnEdit" + produk.getId());
                    btnEdit.setTooltiptext("Klik untuk mengubah data");
                    btnEdit.setImage("/img/edit.png");
                    btnEdit.addEventListener("onClick", new EventListener() {

                        public void onEvent(Event event) throws Exception {
                            produkEdit = produk;
                            txtKode.setValue(produk.getKode());
                            txtNama.setValue(produk.getNama());
                            txtKeterangan.setValue(produk.getKeterangan());
                            txtHarga.setValue(produk.getHargaSatuan());
                            txtKeteranganLengkap.setValue(produk.getKeteranganLengkap());
                        }
                    });

                    Toolbarbutton btnDelete = new Toolbarbutton();
                    btnDelete.setId("btnDelete" + produk.getId());
                    btnDelete.setTooltiptext("Klik untuk menghapus data");
                    btnDelete.setImage("/img/delete.png");
                    btnDelete.addEventListener("onClick", new EventListener() {

                        public void onEvent(Event event) throws Exception {
                            delete(produk);
                        }
                    });
                    Hbox btn = new Hbox();
                    btn.appendChild(btnEdit);
                    btn.appendChild(btnDelete);
                    row.appendChild(btn);
                    row.appendChild(detail);
                    rows.appendChild(row);
                    grid.appendChild(rows);
                }
            } catch (Exception ex) {
                Logger.getLogger(ProdukWnd.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (Exception e) {
            redirect("/zul/login.zul");
        }
    }

    public void loadDataKategori() {
        cmbKategori.getItems().clear();
        try {
            List<Kategori> kategoris = kategoriDAO.gets();
            for (Kategori kategori : kategoris) {
                Comboitem item = new Comboitem();
                item.setValue(kategori.getId());
                item.setLabel(kategori.getNama());
                cmbKategori.appendChild(item);
            }
            cmbKategori.setSelectedIndex(0);
        } catch (Exception ex) {
            Logger.getLogger(ProdukWnd.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void save() throws Exception {
        Kategori kategori = new Kategori();
        kategori.setId(Integer.valueOf(cmbKategori.getSelectedItem().getValue().toString()));

        Vendor vendor = vendorDAO.getByAccount(account.getId());
        Produk produk = new Produk();
        produk.setKode(txtKode.getText());
        produk.setNama(txtNama.getText());
        produk.setKeterangan(txtKeterangan.getText());
        produk.setKeteranganLengkap(txtKeteranganLengkap.getText());
        produk.setHargaSatuan(txtHarga.getValue());
        if (media != null) {
            produk.setNamaGambar(media.getName());
            produk.setFileGambar(media.getStreamData());
        }
        produk.setKategori(kategori);
        produk.setVendor(vendor);

        if (produk.getNama().isEmpty() || produk.getKode().isEmpty() || produk.getVendor().getNama().isEmpty()) {
            Messagebox.show("Data ada yang kosong");
        } else {
            try {
                if (produkEdit == null) {
                    produkDAO.insert(produk);
                } else {
                    produk.setId(produkEdit.getId());
                    if (produk.getFileGambar() == null) {
                        produk.setFileGambar(null);
                    }
                    produkDAO.update(produk);
                }
                Messagebox.show("Data telah disimpan");
                this.loadDataProduk();
                this.clear();
            } catch (Exception exception) {
                exception.printStackTrace();
                Messagebox.show("Gagal menyimpan data produk");
            }
        }
    }

    private void delete(Produk produk) throws InterruptedException {
        try {
            produkDAO.delete(produk.getId());
            Messagebox.show("Data telah dihapus");
            this.loadDataProduk();
        } catch (Exception ex) {
            Logger.getLogger(ProdukWnd.class.getName()).log(Level.SEVERE, null, ex);
            Messagebox.show("Gagal menghapus data");
        }
    }

    public void cancel() {
        this.clear();
    }

    public void clear() {
        produkEdit = null;
        media = null;
        txtKode.setText("");
        txtNama.setText("");
        txtKeterangan.setText("");
        txtKeteranganLengkap.setText("");
        txtHarga.setText("0");
        cmbKategori.setSelectedIndex(0);
        lblUploadStatus.setValue("");
    }

    public void upload(Media media) throws Exception {
        System.out.println(media.getContentType());
        if (media.getContentType().endsWith("jpeg") || media.getContentType().endsWith("png")) {
            if (media.getStreamData().available() > 5242880) {
                Messagebox.show("Ukuran image terlalu besar");
                lblUploadStatus.setValue("");
            } else {
                this.media = media;
                lblUploadStatus.setValue(media.getName());
            }
        } else {
            Messagebox.show("Format tidak sesuai");
            lblUploadStatus.setValue("");
        }
    }

    public void redirect(String url) throws Exception {
        Div contentDiv = (Div) this.getParent();
        contentDiv.getChildren().clear();
        Executions.createComponents(url, contentDiv, null);
    }
}
